import {
  newsCollectList
} from '../../apis/user';
import {
  collectNews
} from '../../apis/index';
import {
  splicing,
  formatTime
} from '../../utils/util';
const app = getApp();

Page({
  data: {
    newsList: [],
    pageNum: 1,
    isHaveMore: true,
    isRequest: false
  },

  onLoad() {

  },

  onShow() {
    this.getNewsCollectList(1, 10);
  },

  onReachBottom() {
    if (this.data.isHaveMore && !this.data.isRequest) {
      this.getNewsCollectList(this.data.pageNum + 1, 10, 'load');
    };
  },

  getNewsCollectList(pageNum, pageSize, type) {
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    newsCollectList(pageNum, pageSize).then(res => {
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        if (type !== 'push') {
          this.setData({
            pageNum: pageNum
          });
        };
        let {
          rows,
          total
        } = res.data;
        rows.forEach(v => {
          v.image = splicing(v.image);
          v.dateTime = formatTime(v.dateTime);
        });
        if (type === 'load') {
          rows.forEach(v => {
            this.data.newsList.push(v);
          });
          this.setData({
            newsList: this.data.newsList
          });
        } else {
          this.setData({
            newsList: rows
          });
        };

        if (this.data.newsList.length === total) {
          this.setData({
            isHaveMore: false
          });
        };
      };
    });
  },

  // 新闻详情
  newsDetails(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/newsDetails/index?newsId=${id}`
    });
  },

  // 收藏
  collectNews(e) {
    let {
      id,
      index
    } = e.currentTarget.dataset;
    wx.showModal({
      content: '确定取消收藏该新闻吗？',
      success: res => {
        if (res.confirm) {
          collectNews(id).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '取消成功',
                duration: 1000,
                icon: 'success',
                mask: true
              });
              this.data.newsList.splice(index, 1);
              this.setData({
                newsList: this.data.newsList
              });
              this.getNewsCollectList(this.data.newsList.length + 1, 1, 'push');
            };
          });
        };
      }
    });
  }
})